# -*- coding: utf-8 -*-

from openerp.osv import osv,fields
from openerp.addons.dftg_weixin.application.application_service import WxAppCWXKF
from openerp.addons.dftg_weixin.application.application_test import WxAppCropTest
SUPERUSER_ID=1

class im_chat_message(osv.osv):
    _inherit = 'im_chat.message'
    _columns = {
        'type': fields.selection([('message', 'Message'), ('meta', 'Meta'),('image','image'),('voice','voice') ], 'Type'),
    }
    def post_and_send_wxm(self, cr, uid, from_uid, uuid, message_type, message_content, context=None):
        self.wx_kf = WxAppCWXKF()
        self.wx_kf.odoo_system_to_wixin_kf(from_uid, uuid, message_type, message_content)
        return self.post(cr, uid, from_uid=from_uid, uuid=uuid, message_type='weixin_message',
                                                  message_content=message_content, context=context)
    # 客服发送消息引起正常发送消息异常 -- 暂时取消
    # def post(self, cr, uid, from_uid, uuid, message_type, message_content, context=None):
    #     wx_api_sed_text = WxAppCropTest()
    #     if message_type == 'message':
    #         session_id = self.pool.get('im_chat.session').search(cr, SUPERUSER_ID,
    #                                                              [('uuid', '=', uuid)],
    #                                                              order='write_date desc', context=context)
    #         session_id_objs = self.pool.get('im_chat.session').browse(cr, SUPERUSER_ID, session_id, context=context)
    #         user_ids = list(set([user.id for user in session_id_objs.user_ids]) - set([from_uid]))
    #         if not user_ids:
    #             user_ids = from_uid
    #         for users_row in self.pool.get('res.users').browse(cr, SUPERUSER_ID, user_ids):
    #             if self.pool.get('res.users').has_group(cr, users_row.id, 'base.group_sale_salesman') and from_uid:
    #                 contact_id = self.pool.get('weixin.contacts').search(cr, uid, [('odoo_user_id', '=', users_row.id)],
    #                                                                      context=context)
    #                 if contact_id:
    #                     wx_api_sed_text.wxapi.send_text(message_content, wx_api_sed_text.APP_ID, safe="0", touser=str(contact_id[0]))
    #     else:
    #         if message_type != 'image' and message_type != 'voice':
    #             message_type='message'
    #     return super(im_chat_message, self).post(cr, uid, from_uid=from_uid, uuid=uuid, message_type=message_type,
    #                                              message_content=message_content, context=context)

    def post_image_to_kf(self, cr, uid, image, type, from_uid, uuid,message_type, message_content, context=None):
        wx_api_kf = WxAppCWXKF()
        wx_api_kf.send_message_media_to_kf(image, type)
        return self.post(cr, uid, from_uid=from_uid, uuid=uuid, message_type=message_type,
                         message_content=message_content, context=context)
